﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FIPSSearch
{
    class RepositoryBase
    {
        protected string m_ConnectionString;

        public RepositoryBase(string connectionString)
        {
            m_ConnectionString = connectionString;
        }

        /// <summary>
        /// Clears the School District table using SQL command
        /// </summary>
        protected void ClearTable(string tableName)
        {
            //Using ADO.DB
            using (var conn = new SqlConnection(m_ConnectionString))
            {
                conn.Open();
                using (var cmd = new SqlCommand("DELETE FROM " + tableName + ";", conn))
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.ExecuteNonQuery();
                }
            }
            //using EF
            /*
            using (var context = new CensusToolsEntities())
            {
                context.Database.ExecuteSqlCommand("DELETE FROM SchoolDistrict;");
            }
            */
        }

        protected void UploadDataTable(DataTable table, string tableName)
        {
            using (var conn = new SqlConnection(m_ConnectionString))
            {
                conn.Open();
                using (var cmd = new SqlBulkCopy(conn))
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        cmd.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                    }

                    cmd.DestinationTableName = tableName;
                    cmd.WriteToServer(table);
                }
            }
        }
    }
}
